package com.the4man.framework.utils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by lenovo on 2017/12/12.
 */
public class ParameterItem {
    private String parameterName;
    private Object parameterValue;
    private Urlformatable urlformatable;

    public String getParameterName() {
        return this.parameterName;
    }

    public void setParameterName(String parameterName) {
        this.parameterName = parameterName;
    }

    public Object getParameterValue() {
        return this.parameterValue;
    }

    public void setParameterValue(Object parameterValue) {
        this.parameterValue = parameterValue;
    }

    public Urlformatable getUrlformatable() {
        return this.urlformatable;
    }

    public void setUrlformatable(Urlformatable urlformatable) {
        this.urlformatable = urlformatable;
    }

    public ParameterItem(String pname, Object pvalue) {
        this.parameterName = pname;
        this.parameterValue = pvalue;
    }

    public ParameterItem(String pname, Object pvalue, Urlformatable format) {
        this.parameterName = pname;
        this.parameterValue = pvalue;
        this.urlformatable = format;
    }

    public String urlParameterFormat(String charset) throws UnsupportedEncodingException {
        return this.urlformatable != null?this.urlformatable.format(this.parameterName, this.parameterValue, charset):this.defaultFormat(this.parameterName, this.parameterValue, charset);
    }

    public String defaultFormat(String key, Object value, String charset) throws UnsupportedEncodingException {
        if(value == null) {
            return key + "+";
        } else if(value instanceof Date) {
            return key + "=" + (new SimpleDateFormat("yyyy-MM-dd")).format((Date)value);
        } else if(!value.getClass().isArray()) {
            return key + "=" + URLEncoder.encode(value.toString(), charset);
        } else {
            String r = "";

            for(int i = 0; i < Array.getLength(value); ++i) {
                r = r + "&" + key + "=" + Array.get(value, i).toString();
            }

            return r.length() > 0?r.substring(1):"";
        }
    }
}
